package com.edushare.common.dao;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

import com.edushare.common.exceptions.EduShareRuntimeException;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.util.MailUtil;
import com.edushare.common.util.StringUtil;
import com.edushare.common.util.URLUtils;
import com.edushare.common.vo.EmailTemplates;
import com.edushare.common.vo.OutgoingEmails;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class EmailTemplatesDAO extends CayenneBasedDAO {
	
	/**
	 * All keys to Hash-map that is sent to parser
	 */
	public static final String TO_USER_NAME 			= "TO_USER_NAME";
	public static final String FROM_USER_NAME 			= "FROM_USER_NAME";
	public static final String COURSE_NAME 				= "COURSE_NAME";
	public static final String UNIVERSITY_NAME 			= "UNIVERSITY_NAME";
	public static final String DEPARTMENT_NAME 			= "DEPARTMENT_NAME";
	public static final String KEY_URL 					= "KEY_URL";
	public static final String USER_NAME				= "USER_NAME";
	public static final String FROM_USER_URL 			= "FROM_USER_URL";
	public static final String TO_USER_URL 				= "TO_USER_URL";
	public static final String COURSE_URL 				= "COURSE_URL";
	public static final String DEPARTMENT_URL 			= "DEPARTMENT_URL";
	public static final String UNIVERSITY_URL 			= "UNIVERSITY_URL";
	public static final String LANDING_PAGE_URL 		= "LANDING_PAGE_URL";
	public static final String CUSTOM_MESSAGE			= "CUSTOM_MESSAGE";
	
	public EmailTemplatesDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}
	
	@SuppressWarnings("unchecked")
	public EmailTemplates getTemplateObject(int emailTemplateCode) {
		Expression exp = Expression.fromString("templateCode = $emailType");
		HashMap hm = new HashMap();
		hm.put("emailType", emailTemplateCode);
		SelectQuery query = new SelectQuery(EmailTemplates.class, exp.expWithParameters(hm));
		return (EmailTemplates)getDataContext().performQuery(query).get(0);
	}
	
	private String templateParser(String template, HashMap<String, String> contentVariableMap){
		StringBuffer sb = new StringBuffer();
		String regexPattern = "<es:replace>[a-zA-Z0-9_\\-]*</es:replace>";
		Pattern p = Pattern.compile(regexPattern);
		Matcher m = p.matcher(template);
		while(m.find()){
			String key = m.group().replace("<es:replace>", "");
			key = key.replace("</es:replace>", "");
			String replacement = contentVariableMap.get(key);
			if(replacement==null)replacement = "Entity";
			m.appendReplacement(sb, replacement);
		}
		m.appendTail(sb);
		return sb.toString();
	}

	
	public void sendJoinUniversityMailToTeachersWithKey(Users to, Users from, 
											Universities univ, String key, String customMessage){		
		EmailTemplates template = getTemplateObject(EmailTemplates.TEACHER_REGISTRATION_KEY);
		sendJoidUniversityMail(template,to,from, univ, key, customMessage);		
	}
	

	public void sendJoinUniversityMailToStudentsWithKey(Users to, Users from, 
			Universities univ, String key, String customMessage){
		EmailTemplates template = getTemplateObject(EmailTemplates.STUDENT_REGISTRATION_KEY);
		sendJoidUniversityMail(template,to,from, univ, key, customMessage);	
	}	

	public void sendJoinUniversityMailToAdminsWithKey(Users to, Users from, 
			Universities univ, String key, String customMessage){
		EmailTemplates template = getTemplateObject(EmailTemplates.ADMIN_REGISTRATION_KEY);
		sendJoidUniversityMail(template,to,from, univ, key, customMessage);
	}		
	
	public void sendJoidUniversityMail(EmailTemplates template,Users to, Users from, 
			Universities univ, String key, String customMessage){
		
		if(to==null || !StringUtil.isValid(to.getEmail()))
			throw new EduShareRuntimeException("RECIPIENT'S  MAIL ADDRESS IS INAPPROPRIATE.");
		
		if(template==null)
			throw new EduShareRuntimeException("NO SUCH EMAIL TEMPLATE FOUND.");		
		
		HashMap<String, String> contentVariableMap = new HashMap<String, String>();
		String senderName = "";
		senderName = MailUtil.fullUserName(from);
		contentVariableMap.put(FROM_USER_NAME, senderName);
		contentVariableMap.put(FROM_USER_URL, URLUtils.getHomePageURL(from));
		contentVariableMap.put(UNIVERSITY_NAME, univ.getUniversityName());
		contentVariableMap.put(UNIVERSITY_URL, URLUtils.getHomePageURL(univ));
		contentVariableMap.put(KEY_URL, URLUtils.generateTeacherInviteURL(key));
		contentVariableMap.put(CUSTOM_MESSAGE, customMessage);
		
		String mailContent = templateParser(template.getTemplateText(), contentVariableMap);
		OutgoingEmails mail = new OutgoingEmails();
		mail.setContent(mailContent);
		mail.setReceiverEmailId(to.getEmail());
		mail.setStatus(OutgoingEmails.EMAIL_TO_BE_SENT);
		mail.setCopyType(1);
		mail.setSubject("EduShare Registration Verification.");
		getDataContext().registerNewObject(mail);
		getDataContext().commitChanges();
	}
	
	public void sendPasswordResetMail(EmailTemplates template, Users to, String key){
		if(to==null || !StringUtil.isValid(to.getEmail()))
			throw new EduShareRuntimeException("RECIPIENT'S  MAIL ADDRESS IS INAPPROPRIATE.");
		
		if(template==null)
			throw new EduShareRuntimeException("NO SUCH EMAIL TEMPLATE FOUND.");		

		HashMap<String, String> contentVariableMap = new HashMap<String, String>();
		contentVariableMap.put(KEY_URL, URLUtils.generatePasswordResetURL(key));
		contentVariableMap.put(USER_NAME, to.getUserName());
		String mailContent = templateParser(template.getTemplateText(), contentVariableMap);
		OutgoingEmails mail = new OutgoingEmails();
		mail.setContent(mailContent);
		mail.setReceiverEmailId(to.getEmail());
		mail.setStatus(OutgoingEmails.EMAIL_TO_BE_SENT);
		mail.setCopyType(1);
		mail.setSubject("EduShare Registration Verification.");
		getDataContext().registerNewObject(mail);
		getDataContext().commitChanges();

	}
}
